package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Switch;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.CheckBox;
import android.app.DatePickerDialog;
import java.text.SimpleDateFormat;
import java.util.Locale;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.example.mydy.adapter.UserPrivilegeAdapter;
import com.example.mydy.model.UserRewardPrivilege;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.datepicker.MaterialDatePicker;
import java.util.Calendar;
import java.util.Date;

public class TaskRewardManagement extends AppCompatActivity {
    private static final String TAG = "TaskRewardManagement";

    // 全局设置相关视图
    private EditText etSingleTaskReward, etLevel1TaskRatio, etLevel2TaskRatio, etLevel3TaskRatio;
    private EditText etLevel1InviteReward, etLevel2InviteReward, etLevel3InviteReward;
    private Spinner spinnerTaskStatus, spinnerInviteStatus;

    // 任务奖励设置相关视图
    private EditText etTaskReward, etLevel1TaskSplit, etLevel2TaskSplit, etLevel3TaskSplit;
    private Spinner spinnerTaskEnable;

    // 邀请奖励设置相关视图
    private EditText etInviteRewardAmount;
    private Spinner spinnerInviteEnable;

    // 用户专属奖励设置相关视图
    private EditText etUserId;
    private EditText etUserTaskReward, etUserLevel1Invite, etUserLevel2Invite, etUserLevel3Invite;
    private EditText etUserLevel1TaskSplit, etUserLevel2TaskSplit, etUserLevel3TaskSplit;

    // 按钮
    private Button btnSave, btnNavHome, btnLogout;

    // 用户特权奖励相关
    private RecyclerView recyclerViewPrivileges;
    private FloatingActionButton fabAddPrivilege;
    private List<UserRewardPrivilege> privilegeList;
    private UserPrivilegeAdapter privilegeAdapter;
    private Date selectedStartDate = null;
    private Date selectedEndDate = null;

    // SharedPreferences 用于保存设置
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_reward_management);

        // 初始化 SharedPreferences
        sharedPreferences = getSharedPreferences("RewardSettings", MODE_PRIVATE);

        // 初始化视图
        initViews();

        // 设置下拉菜单数据
        setupSpinnerData();

        // 设置按钮点击事件
        setupButtonListeners();

        // 加载保存的设置
        loadSavedSettings();

        // 初始化用户特权奖励列表
        initPrivilegeList();
    }

    private void initViews() {
        // 任务奖励设置相关视图 - 从XML布局适配
        etTaskReward = findViewById(R.id.taskRewardAmount);
        etLevel1TaskSplit = findViewById(R.id.taskLevel1Percentage);
        etLevel2TaskSplit = findViewById(R.id.taskLevel2Percentage);
        etLevel3TaskSplit = findViewById(R.id.taskLevel3Percentage);
        spinnerTaskEnable = null; // 对应Switch控件 taskRewardSwitch
        
        // 使用Switch代替Spinner
        Switch taskRewardSwitch = findViewById(R.id.taskRewardSwitch);
        if (taskRewardSwitch != null) {
            taskRewardSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
                // 启用或禁用任务奖励相关控件
                if (etTaskReward != null) etTaskReward.setEnabled(isChecked);
                if (etLevel1TaskSplit != null) etLevel1TaskSplit.setEnabled(isChecked);
                if (etLevel2TaskSplit != null) etLevel2TaskSplit.setEnabled(isChecked);
                if (etLevel3TaskSplit != null) etLevel3TaskSplit.setEnabled(isChecked);
            });
        }

        // 邀请奖励设置相关视图
        etInviteRewardAmount = findViewById(R.id.inviteRewardAmount);
        spinnerInviteEnable = null; // 对应Switch控件 inviteRewardSwitch
        
        // 使用Switch代替Spinner
        Switch inviteRewardSwitch = findViewById(R.id.inviteRewardSwitch);
        if (inviteRewardSwitch != null) {
            inviteRewardSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
                // 启用或禁用邀请奖励相关控件
                if (etInviteRewardAmount != null) etInviteRewardAmount.setEnabled(isChecked);
            });
        }

        // 按钮
        btnSave = findViewById(R.id.saveSettingsButton);
        btnNavHome = findViewById(R.id.nav_home); // 这可能不存在，需要添加处理
        btnLogout = findViewById(R.id.logout_button); // 这也可能不存在，需要添加处理

        // 初始化用户特权奖励相关视图
        recyclerViewPrivileges = findViewById(R.id.recyclerViewPrivileges);
        if (recyclerViewPrivileges == null) {
            // 如果XML中没有定义该视图，可以动态添加或者修改布局
            Log.d("TaskReward", "用户特权列表视图未定义，跳过初始化");
        }
        
        fabAddPrivilege = findViewById(R.id.fabAddPrivilege);
        if (fabAddPrivilege == null) {
            Log.d("TaskReward", "添加特权按钮未定义，跳过初始化");
        } else {
            fabAddPrivilege.setOnClickListener(v -> showAddPrivilegeDialog());
        }
    }

    private void setupSpinnerData() {
        // 在当前布局中不再使用Spinner控件，改用Switch
        // 这个方法目前不需要执行任何操作
        
        // 如果以后需要使用下拉菜单，可以在这里添加相关代码
    }

    private void setupButtonListeners() {
        // 保存按钮点击事件
        if (btnSave != null) {
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveSettings();
            }
        });
        }

        // 如果首页按钮不存在，则动态创建返回按钮
        if (btnNavHome == null) {
            // 尝试在界面上找一个合适的容器添加返回按钮
            findViewById(R.id.saveSettingsButton).setOnLongClickListener(v -> {
                onBackPressed(); // 长按保存按钮返回
                return true;
            });
        } else {
        btnNavHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 修改跳转目标为 AdminActivity
                Intent intent = new Intent(TaskRewardManagement.this, AdminActivity.class);
                startActivity(intent);
                finish();
            }
        });
        }

        // 如果退出按钮不存在，可以忽略这个功能
        if (btnLogout != null) {
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清除登录信息
                getSharedPreferences("MyAppPrefs", MODE_PRIVATE).edit().clear().apply();
                Intent intent = new Intent(TaskRewardManagement.this, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        });
        }
    }

    private void saveSettings() {
        // 获取任务奖励设置数据
        String taskReward = etTaskReward != null ? etTaskReward.getText().toString() : "";
        String level1TaskSplit = etLevel1TaskSplit != null ? etLevel1TaskSplit.getText().toString() : "";
        String level2TaskSplit = etLevel2TaskSplit != null ? etLevel2TaskSplit.getText().toString() : "";
        String level3TaskSplit = etLevel3TaskSplit != null ? etLevel3TaskSplit.getText().toString() : "";
        
        // 获取任务奖励开关状态
        Switch taskRewardSwitch = findViewById(R.id.taskRewardSwitch);
        boolean taskRewardEnabled = taskRewardSwitch != null && taskRewardSwitch.isChecked();

        // 获取邀请奖励设置数据
        String inviteRewardAmount = etInviteRewardAmount != null ? etInviteRewardAmount.getText().toString() : "";
        
        // 获取邀请奖励开关状态
        Switch inviteRewardSwitch = findViewById(R.id.inviteRewardSwitch);
        boolean inviteRewardEnabled = inviteRewardSwitch != null && inviteRewardSwitch.isChecked();

        // 保存设置到 SharedPreferences
        SharedPreferences.Editor editor = sharedPreferences.edit();
        
        // 保存任务奖励设置
        editor.putString("taskReward", taskReward);
        editor.putString("level1TaskSplit", level1TaskSplit);
        editor.putString("level2TaskSplit", level2TaskSplit);
        editor.putString("level3TaskSplit", level3TaskSplit);
        editor.putBoolean("taskRewardEnabled", taskRewardEnabled);
        
        // 保存邀请奖励设置
        editor.putString("inviteRewardAmount", inviteRewardAmount);
        editor.putBoolean("inviteRewardEnabled", inviteRewardEnabled);
        
        // 添加更多的配置标记，以区分不同类型的奖励
        editor.putBoolean("useCustomUserSettings", true);
        editor.putBoolean("separateRewardFromBounty", true); // 标记悬赏任务和普通任务奖励是分开的
        
        editor.apply();

        // 显示保存成功提示
        Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
    }

    private void loadSavedSettings() {
        // 从 SharedPreferences 加载保存的设置
        
        // 加载任务奖励设置
        if (etTaskReward != null) {
            etTaskReward.setText(sharedPreferences.getString("taskReward", "100"));
        }
        if (etLevel1TaskSplit != null) {
            etLevel1TaskSplit.setText(sharedPreferences.getString("level1TaskSplit", "50"));
        }
        if (etLevel2TaskSplit != null) {
            etLevel2TaskSplit.setText(sharedPreferences.getString("level2TaskSplit", "25"));
        }
        if (etLevel3TaskSplit != null) {
            etLevel3TaskSplit.setText(sharedPreferences.getString("level3TaskSplit", "10"));
        }
        
        // 加载开关状态
        Switch taskRewardSwitch = findViewById(R.id.taskRewardSwitch);
        if (taskRewardSwitch != null) {
            taskRewardSwitch.setChecked(sharedPreferences.getBoolean("taskRewardEnabled", true));
        }
        
        // 加载邀请奖励设置
        if (etInviteRewardAmount != null) {
            etInviteRewardAmount.setText(sharedPreferences.getString("inviteRewardAmount", "2"));
        }
        
        // 加载邀请开关状态
        Switch inviteRewardSwitch = findViewById(R.id.inviteRewardSwitch);
        if (inviteRewardSwitch != null) {
            inviteRewardSwitch.setChecked(sharedPreferences.getBoolean("inviteRewardEnabled", true));
        }
        
        // 根据开关状态启用或禁用相关控件
        if (taskRewardSwitch != null && etTaskReward != null) {
            boolean enabled = taskRewardSwitch.isChecked();
            etTaskReward.setEnabled(enabled);
            if (etLevel1TaskSplit != null) etLevel1TaskSplit.setEnabled(enabled);
            if (etLevel2TaskSplit != null) etLevel2TaskSplit.setEnabled(enabled);
            if (etLevel3TaskSplit != null) etLevel3TaskSplit.setEnabled(enabled);
        }
        
        if (inviteRewardSwitch != null) {
            boolean enabled = inviteRewardSwitch.isChecked();
            if (etInviteRewardAmount != null) etInviteRewardAmount.setEnabled(enabled);
        }
    }

    // 初始化用户特权奖励列表
    private void initPrivilegeList() {
        // 如果recyclerViewPrivileges为空或在XML中不存在，跳过初始化
        if (recyclerViewPrivileges == null) {
            Log.d(TAG, "recyclerViewPrivileges is null, skipping initialization");
            return;
        }
        
        privilegeList = new ArrayList<>();
        privilegeAdapter = new UserPrivilegeAdapter(privilegeList, this::confirmDeletePrivilege, this::showEditPrivilegeDialog);
        recyclerViewPrivileges.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewPrivileges.setAdapter(privilegeAdapter);
        
        // 加载用户特权奖励数据
        reloadPrivilegeList();
    }
    
    // 显示添加用户特权奖励对话框
    private void showAddPrivilegeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_user_privilege, null);
        builder.setView(dialogView);
        
        // 获取视图
        EditText etUsername = dialogView.findViewById(R.id.et_username);
        EditText etLevel1Ratio = dialogView.findViewById(R.id.et_level1_ratio);
        EditText etLevel2Ratio = dialogView.findViewById(R.id.et_level2_ratio);
        EditText etLevel3Ratio = dialogView.findViewById(R.id.et_level3_ratio);
        EditText etInviteReward = dialogView.findViewById(R.id.et_invite_reward);
        EditText etRemark = dialogView.findViewById(R.id.et_remark);
        Button btnStartDate = dialogView.findViewById(R.id.btn_start_date);
        Button btnEndDate = dialogView.findViewById(R.id.btn_end_date);
        CheckBox cbNoEndDate = dialogView.findViewById(R.id.cb_no_end_date);
        
        // 设置默认值
        etLevel1Ratio.setText("50");
        etLevel2Ratio.setText("25");
        etLevel3Ratio.setText("10");
        etInviteReward.setText("2");
        
        // 设置日期选择
        selectedStartDate = new Date(); // 默认为今天
        selectedEndDate = null;
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        btnStartDate.setText("开始日期: " + dateFormat.format(selectedStartDate));
        
        btnStartDate.setOnClickListener(v -> {
            showDatePicker(true, btnStartDate);
        });
        
        btnEndDate.setOnClickListener(v -> {
            showDatePicker(false, btnEndDate);
        });
        
        // 无结束日期复选框
        cbNoEndDate.setOnCheckedChangeListener((buttonView, isChecked) -> {
            btnEndDate.setEnabled(!isChecked);
            if (isChecked) {
                selectedEndDate = null;
                btnEndDate.setText("结束日期: 永久");
            }
        });
        
        // 创建对话框
        AlertDialog dialog = builder.create();
        dialog.show();
        
        // 添加确定和取消按钮
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", (dialogInterface, i) -> {
            // 验证输入
            String username = etUsername.getText().toString().trim();
            if (username.isEmpty()) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            try {
                double level1Ratio = Double.parseDouble(etLevel1Ratio.getText().toString().trim());
                double level2Ratio = Double.parseDouble(etLevel2Ratio.getText().toString().trim());
                double level3Ratio = Double.parseDouble(etLevel3Ratio.getText().toString().trim());
                double inviteReward = Double.parseDouble(etInviteReward.getText().toString().trim());
                String remark = etRemark.getText().toString().trim();
                
                // 创建用户特权奖励对象
                UserRewardPrivilege privilege = new UserRewardPrivilege();
                privilege.setUsername(username);
                privilege.setLevel1Ratio(level1Ratio);
                privilege.setLevel2Ratio(level2Ratio);
                privilege.setLevel3Ratio(level3Ratio);
                privilege.setInviteReward(inviteReward);
                privilege.setStartDate(selectedStartDate);
                privilege.setEndDate(selectedEndDate);
                privilege.setRemark(remark);
                
                // 保存到模拟数据库
                boolean success = MockDataManager.addUserRewardPrivilege(privilege);
                if (success) {
                    // 刷新列表
                    reloadPrivilegeList();
                    Toast.makeText(this, "添加用户特权奖励成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "添加失败，请重试", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
            }
        });
        
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialogInterface, i) -> {
            dialog.dismiss();
        });
    }
    
    // 显示编辑用户特权奖励对话框
    private void showEditPrivilegeDialog(UserRewardPrivilege privilege, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_user_privilege, null);
        builder.setView(dialogView);
        
        // 获取视图
        EditText etUsername = dialogView.findViewById(R.id.et_username);
        EditText etLevel1Ratio = dialogView.findViewById(R.id.et_level1_ratio);
        EditText etLevel2Ratio = dialogView.findViewById(R.id.et_level2_ratio);
        EditText etLevel3Ratio = dialogView.findViewById(R.id.et_level3_ratio);
        EditText etInviteReward = dialogView.findViewById(R.id.et_invite_reward);
        EditText etRemark = dialogView.findViewById(R.id.et_remark);
        Button btnStartDate = dialogView.findViewById(R.id.btn_start_date);
        Button btnEndDate = dialogView.findViewById(R.id.btn_end_date);
        CheckBox cbNoEndDate = dialogView.findViewById(R.id.cb_no_end_date);
        
        // 设置当前值
        etUsername.setText(privilege.getUsername());
        etUsername.setEnabled(false); // 不允许修改用户名
        etLevel1Ratio.setText(String.valueOf(privilege.getLevel1Ratio()));
        etLevel2Ratio.setText(String.valueOf(privilege.getLevel2Ratio()));
        etLevel3Ratio.setText(String.valueOf(privilege.getLevel3Ratio()));
        etInviteReward.setText(String.valueOf(privilege.getInviteReward()));
        etRemark.setText(privilege.getRemark());
        
        // 设置日期
        selectedStartDate = privilege.getStartDate();
        selectedEndDate = privilege.getEndDate();
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        if (selectedStartDate != null) {
            btnStartDate.setText("开始日期: " + dateFormat.format(selectedStartDate));
        }
        
        if (selectedEndDate != null) {
            btnEndDate.setText("结束日期: " + dateFormat.format(selectedEndDate));
        } else {
            btnEndDate.setText("结束日期: 永久");
            cbNoEndDate.setChecked(true);
            btnEndDate.setEnabled(false);
        }
        
        btnStartDate.setOnClickListener(v -> {
            showDatePicker(true, btnStartDate);
        });
        
        btnEndDate.setOnClickListener(v -> {
            showDatePicker(false, btnEndDate);
        });
        
        // 无结束日期复选框
        cbNoEndDate.setOnCheckedChangeListener((buttonView, isChecked) -> {
            btnEndDate.setEnabled(!isChecked);
            if (isChecked) {
                selectedEndDate = null;
                btnEndDate.setText("结束日期: 永久");
            }
        });
        
        // 创建对话框
        AlertDialog dialog = builder.create();
        dialog.show();
        
        // 添加确定和取消按钮
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "保存", (dialogInterface, i) -> {
            try {
                double level1Ratio = Double.parseDouble(etLevel1Ratio.getText().toString().trim());
                double level2Ratio = Double.parseDouble(etLevel2Ratio.getText().toString().trim());
                double level3Ratio = Double.parseDouble(etLevel3Ratio.getText().toString().trim());
                double inviteReward = Double.parseDouble(etInviteReward.getText().toString().trim());
                String remark = etRemark.getText().toString().trim();
                
                // 更新用户特权奖励对象
                privilege.setLevel1Ratio(level1Ratio);
                privilege.setLevel2Ratio(level2Ratio);
                privilege.setLevel3Ratio(level3Ratio);
                privilege.setInviteReward(inviteReward);
                privilege.setStartDate(selectedStartDate);
                privilege.setEndDate(selectedEndDate);
                privilege.setRemark(remark);
                
                // 保存到模拟数据库
                boolean success = MockDataManager.updateUserRewardPrivilege(privilege);
                if (success) {
                    // 刷新列表
                    reloadPrivilegeList();
                    Toast.makeText(this, "更新用户特权奖励成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "更新失败，请重试", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
            }
        });
        
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialogInterface, i) -> {
            dialog.dismiss();
        });
    }
    
    // 确认删除对话框
    private void confirmDeletePrivilege(int id, int position) {
        new AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定要删除此用户特权奖励设置吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                boolean success = MockDataManager.deleteUserRewardPrivilege(id);
                if (success) {
                    privilegeList.remove(position);
                    privilegeAdapter.notifyItemRemoved(position);
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    // 显示日期选择器
    private void showDatePicker(boolean isStartDate, Button dateButton) {
        Calendar calendar = Calendar.getInstance();
        if (isStartDate && selectedStartDate != null) {
            calendar.setTime(selectedStartDate);
        } else if (!isStartDate && selectedEndDate != null) {
            calendar.setTime(selectedEndDate);
        }
        
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, selectedYear, selectedMonth, selectedDayOfMonth) -> {
            calendar.set(selectedYear, selectedMonth, selectedDayOfMonth);
            Date selectedDate = calendar.getTime();
            
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            if (isStartDate) {
                selectedStartDate = selectedDate;
                dateButton.setText("开始日期: " + dateFormat.format(selectedDate));
            } else {
                selectedEndDate = selectedDate;
                dateButton.setText("结束日期: " + dateFormat.format(selectedDate));
            }
        }, year, month, day);
        
        datePickerDialog.show();
    }
    
    // 重新加载用户特权奖励列表
    private void reloadPrivilegeList() {
        if (recyclerViewPrivileges == null) {
            return;
        }
        
        privilegeList.clear();
        privilegeList.addAll(MockDataManager.getUserRewardPrivileges());
        privilegeAdapter.notifyDataSetChanged();
    }
}